package com.smw.myrealm;

import com.smw.pojo.User;
import com.smw.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class Myrealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行doGetAuthorizationInfo方法，查询用户权限信息方法") ;
        String name=(String)principalCollection.getPrimaryPrincipal();
        //System.out.println("naem:"+name);
        Set<String> roles=userService.findRole(name);
        //System.out.println("roles:"+roles);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("用户的登录");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;

        String userName=(String)token.getPrincipal();
        User u=userService.findPwdByName(userName);
        //System.out.println(u);
        if (u==null){
            throw new AuthenticationException();
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
                userName,
                u.getPassWord(),
                ByteSource.Util.bytes("106"),
                this.getName()
        );
        return info;
    }
}
